Page({
  data: {
    userName: "",
    headImg: "",
    db: {},
    userinfo: {},
    about: "none",
    imageBase64: [],
    openid: "" // 确保在 data 中定义 openid
  },

  getUserProfile(e) {
    var that = this;
    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (res) => {
        wx.setStorageSync('userinfo', res.userInfo);
        
        that.setData({
          userName: res.userInfo.nickName,
          headImg: res.userInfo.avatarUrl,
          home: res.userInfo.city
        });

        // 先获取 openid，然后再保存用户信息
        wx.cloud.callFunction({
          name: 'login',
          data: {},
          success: loginRes => {
            const openid = loginRes.result.openid;
            wx.setStorageSync('openId', openid); // 只存储 openid 字符串
            
            // 使用正确的 openid 保存用户信息
            const db = wx.cloud.database({
              env: "cloud-found-5gjykn4j0bc454c0"
            });
            
            db.collection('user').add({
              data: {
                _openid: openid, // 添加 _openid 字段
                userName: res.userInfo.nickName,
                headImg: res.userInfo.avatarUrl,
                home: res.userInfo.city,
                schoolId: "未填写",
                call: "未填写"
              },
              success: () => {
                wx.reLaunch({ 
                  url: "../index/index"
                });
              }
            });
          },
          fail: err => {
            console.error('获取 openid 失败:', err);
            wx.showToast({
              title: '登录失败',
              icon: 'none'
            });
          }
        });
      }
    });
  },

  onLoad() {
    if (wx.getStorageSync('userinfo')) {
      wx.showLoading({
        title: '数据加载中...',
      });

      const userinfo = wx.getStorageSync('userinfo');
      const openid = wx.getStorageSync('openId'); // 直接获取存储的 openid
      
      this.setData({
        userinfo,
        openid: openid || "" // 处理 openid 不存在的情况
      });
      
      var that = this;
      const db = wx.cloud.database({
        env: "cloud-found-5gjykn4j0bc454c0"
      });
      
      // 只有当 openid 存在时才查询用户信息
      if (openid) {
        db.collection('user').where({
          _openid: openid
        }).get({
          success: function(res) {
            if (res.data && res.data.length > 0) {
              that.setData({
                headImg: res.data[0].headImg,
                userName: res.data[0].userName,
                schoolId: res.data[0].schoolId,
                call: res.data[0].call
              });
            }
          },
          fail: function(err) {
            console.error('查询用户信息失败:', err);
          }
        });

        // 提取用户发布的物品信息
        db.collection('loseThing').where({
          _openid: openid
        }).get({
          success: function(res) {
            let arr = [];
            let length = res.data.length > 3 ? 3 : res.data.length;
            for(let i = 0; i < length; i++) {
              arr.push(res.data[i]);
            }
            that.setData({
              imageBase64: arr
            });
            wx.hideLoading();
          },
          fail: function(err) {
            console.error('查询物品信息失败:', err);
            wx.hideLoading();
          }
        });
      } else {
        wx.hideLoading();
      }
    }
  },

  onPullDownRefresh: function() {
    this.onLoad();
    wx.stopPullDownRefresh();
  },

  showPop() {
    this.setData({
      about: this.data.about === "none" ? "block" : "none"
    });
  }
});